package com.wu.foodsafetyplayer.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityOptions;
import android.app.AppOpsManager;
import android.app.KeyguardManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Looper;
import android.os.PowerManager;
import android.text.TextUtils;
import android.util.Log;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;


public class BaseUtil {
    private static final String TAG = BaseUtil.class.getSimpleName();
    private static android.os.Handler handler = new android.os.Handler(Looper.getMainLooper());

    /**
     * @param mContext
     * @param c
     * @return
     */
    public static int getActivityTaskId(Context mContext, Class<?> c) {
        String topActivityName = "";
        ActivityManager am = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> runningTasks = am.getRunningTasks(5);
        if (runningTasks != null && !runningTasks.isEmpty()) {
            ActivityManager.RunningTaskInfo taskInfo = runningTasks.get(0);
            topActivityName = taskInfo.topActivity.getClassName();
            if (c.getName().equals(topActivityName)) {
                return taskInfo.id;
            }
        }
        return 0;
    }

    /**
     * 判断act是否在栈顶
     *
     * @param mContext
     * @param c
     * @return
     */
    public static boolean getTopApp(Context mContext, Class<?> c) {
        String topActivityName = "";
        ActivityManager am = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> runningTasks = am.getRunningTasks(5);
        if (runningTasks != null && !runningTasks.isEmpty()) {
            ActivityManager.RunningTaskInfo taskInfo = runningTasks.get(0);
            topActivityName = taskInfo.topActivity.getClassName();
        }
        if (c.getName().equals(topActivityName)) {
            return true;
        }

        if (isRunning(mContext) == 1) {
            Log.e(TAG, "方法2获取app是否在运行 ");
            return true;
        }
        return false;
    }


    /**
     * 判断app是否在运行
     *
     * @param context
     * @return
     */
    public static boolean isBackgroundRunning(Context context) {
        ActivityManager activityManager = (ActivityManager) context.getSystemService(context.ACTIVITY_SERVICE);
        if (activityManager == null) {
            return false;
        }
        List<ActivityManager.RunningTaskInfo> processList = activityManager.getRunningTasks(100);
        for (ActivityManager.RunningTaskInfo info : processList) {
            if (info.baseActivity.getPackageName().startsWith(context.getPackageName())) {
                return true;
            }
        }
        return false;
    }

    /**
     * app运行状态 0不运行 1前台 2后台
     *
     * @param context
     * @return
     */
    public static int isRunning(Context context) {
        ActivityManager activityManager = (ActivityManager) context.getSystemService(context.ACTIVITY_SERVICE);
        if (activityManager == null) {
            return 0;
        }
        List<ActivityManager.RunningTaskInfo> processList = activityManager.getRunningTasks(100);
        if (processList.get(0).topActivity.getPackageName().equals(context.getPackageName())) {
            return 1;
        } else {
            for (ActivityManager.RunningTaskInfo info : processList) {
                if (info.baseActivity.getPackageName().startsWith(context.getPackageName())) {
                    return 2;
                }
            }
        }
        return 0;
    }

    /**
     * 堆栈调度，将应用推向前台
     *
     * @param context
     * @param Class
     */
    public static void isRunningForegroundToApp(Context context, final Class Class) {
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        //利用系统方法获取当前Task堆栈, 数目可按实际情况来规划，这里只是演示
        List<ActivityManager.RunningTaskInfo> taskInfoList = activityManager.getRunningTasks(20);

        for (ActivityManager.RunningTaskInfo taskInfo : taskInfoList) {
            //遍历找到本应用的 task，并将它切换到前台
            if (taskInfo.baseActivity.getPackageName().equals(context.getPackageName())) {
                activityManager.moveTaskToFront(taskInfo.id, ActivityManager.MOVE_TASK_WITH_HOME);
                Intent intent = new Intent(context, Class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
                context.startActivity(intent);
                break;
            }
        }
    }

    /**
     * 小米后台弹出界面检测方法
     *
     * @param context
     * @return
     */
    public static boolean canBackgroundStart(Context context) {
        AppOpsManager ops = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            ops = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
        }
        try {
            int op = 10021;
            Method method = ops.getClass().getMethod("checkOpNoThrow", new Class[]{int.class, int.class, String.class});
            Integer result = (Integer) method.invoke(ops, op, android.os.Process.myUid(), context.getPackageName());
            return result == AppOpsManager.MODE_ALLOWED;
        } catch (Exception e) {
        }
        return false;
    }

    /**
     * 判断vivo后台弹出界面
     *
     * @param context
     * @return
     */
    public static boolean getvivoBgStartActivityPermissionStatus(Context context) {
        String packageName = context.getPackageName();
        Uri uri2 = Uri.parse("content://com.vivo.permissionmanager.provider.permission/start_bg_activity");
        String selection = "pkgname = ?";
        String[] selectionArgs = new String[]{packageName};
        try {
            Cursor cursor = context
                    .getContentResolver()
                    .query(uri2, null, selection, selectionArgs, null);
            if (cursor != null) {
                if (cursor.moveToFirst()) {
                    int currentmode = cursor.getInt(cursor.getColumnIndex("currentstate"));
                    cursor.close();

                    return currentmode == 0;
                } else {
                    cursor.close();
                    return false;
                }
            }
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return false;
    }

    /**
     * 设置act透明
     *
     * @param activity
     */
    public static void translucentActivity(Activity activity) {
        try {
            activity.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            activity.getWindow().getDecorView().setBackground(null);
            Method activityOptions = Activity.class.getDeclaredMethod("getActivityOptions");
            activityOptions.setAccessible(true);
            Object options = activityOptions.invoke(activity);

            Class<?>[] classes = Activity.class.getDeclaredClasses();
            Class<?> aClass = null;
            for (Class clazz : classes) {
                if (clazz.getSimpleName().contains("TranslucentConversionListener")) {
                    aClass = clazz;
                }
            }
            Method method = Activity.class.getDeclaredMethod("convertToTranslucent",
                    aClass, ActivityOptions.class);
            method.setAccessible(true);
            method.invoke(activity, null, options);
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }


    /**
     * 判断服务是否开启
     *
     * @return
     */
    public static boolean isServiceRunning(Context context, String ServiceName) {
        if (TextUtils.isEmpty(ServiceName)) {
            return false;
        }
        ActivityManager myManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        ArrayList<ActivityManager.RunningServiceInfo> runningService = (ArrayList<ActivityManager.RunningServiceInfo>) myManager.getRunningServices(1000);
        for (int i = 0; i < runningService.size(); i++) {
//            Log.i("服务运行1：",""+runningService.get(i).service.getClassName().toString());
            if (runningService.get(i).service.getClassName().toString().equals(ServiceName)) {
                return true;
            }
        }
        return false;
    }


    /**
     * 返回主页
     *
     * @param context
     * @param delay
     */
    public static void perforGlobalHome(final Context context, long delay) {
        Intent home = new Intent(Intent.ACTION_MAIN);
        home.addCategory(Intent.CATEGORY_HOME);
        home.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(home);

        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                Intent home = new Intent(Intent.ACTION_MAIN);
                home.addCategory(Intent.CATEGORY_HOME);
                home.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(home);
            }
        }, delay);
    }


    /**
     * -------------------------------SharedPreferences缓存相关-----------------------------------------------------------------------------------
     */
    /**
     * 是否第一次打开
     *
     * @param context
     * @return
     */
    public static boolean isFirstStart(Context context) {
        SharedPreferences preferences = context.getSharedPreferences("SHARE_APP_TAG", 0);
        Boolean isFirst = preferences.getBoolean("FIRSTStart", true);
        if (isFirst) {// 第一次
            preferences.edit().putBoolean("FIRSTStart", false).commit();
            return true;
        } else {
            return false;
        }
    }

    /**
     * 是否试用过
     *
     * @param context
     * @return
     */
    public static boolean istrial(Context context) {
        SharedPreferences preferences = context.getSharedPreferences("SHARE_APP_TAG", 0);
        String isFirst = preferences.getString("istrial", "true");
        return isFirst.equals("true");
    }

    /**
     * 设置试用过
     *
     * @param context
     */
    public static void settrial(Context context) {
        SharedPreferences preferences = context.getSharedPreferences("SHARE_APP_TAG", 0);
        preferences.edit().putString("istrial", "false").commit();
    }

    /**
     * act是否在打开，用于设置权限时避免后台自动启动页面
     *
     * @param context
     * @return
     */
    public static boolean actIsTop(Context context) {
        SharedPreferences preferences = context.getSharedPreferences("SHARE_APP_TAG", 0);
        return preferences.getBoolean("ACT_TOP", true);
    }

    /**
     * 设置不提示开机自启权限的弹框
     *
     * @param context
     */
    public static void setUnOutStartDialog(Context context) {
        SharedPreferences preferences = context.getSharedPreferences("SHARE_APP_TAG", 0);
        preferences.edit().putBoolean("IS_SHOW_OUT_START", false).commit();
    }

    /**
     * 是否显示提示开机自启选项弹框
     *
     * @param context
     * @return
     */
    public static boolean isShowOutStartDialog(Context context) {
        SharedPreferences preferences = context.getSharedPreferences("SHARE_APP_TAG", 0);
        return preferences.getBoolean("IS_SHOW_OUT_START", true);
    }


    /**
     * 保存用户登录信息
     *
     * @param context
     * @param userInfo
     */
    public static void saveUserInfo(Context context, String userInfo) {
        SharedPreferences preferences = context.getSharedPreferences("SHARE_APP_TAG", 0);
        preferences.edit().putString("userInfo", userInfo).commit();
    }


    /**
     * 保存用户登录信息
     *
     * @param context
     * @param status
     */
    public static void saveUserStatus(Context context, String status) {
        SharedPreferences preferences = context.getSharedPreferences("SHARE_APP_TAG", 0);
        preferences.edit().putString("user_status", status).commit();
    }


    /**
     * 获取当前用户使用状态
     *
     * @param context
     * @return
     */
    public static String getUserStatus(Context context) {
        SharedPreferences preferences = context.getSharedPreferences("SHARE_APP_TAG", 0);
        return preferences.getString("userInfo", null);
    }


    /**
     * 保存号码
     *
     * @param context
     */
    public static void savePhone(Context context, String phone) {
        SharedPreferences preferences = context.getSharedPreferences("SHARE_APP_TAG", 0);
        preferences.edit().putString("phone", phone).commit();
    }


    /**
     * 获取当号码态
     *
     * @param context
     * @return
     */
    public static String getPhone(Context context) {
        SharedPreferences preferences = context.getSharedPreferences("SHARE_APP_TAG", 0);
        return preferences.getString("phone", null);
    }

    /**
     * 保存验证码Code
     *
     * @param context
     */
    public static void saveCode(Context context, String phone) {
        SharedPreferences preferences = context.getSharedPreferences("SHARE_APP_TAG", 0);
        preferences.edit().putString("Code", phone).commit();
    }


    /**
     * 获取当验证码Code
     *
     * @param context
     * @return
     */
    public static String getCode(Context context) {
        SharedPreferences preferences = context.getSharedPreferences("SHARE_APP_TAG", 0);
        return preferences.getString("Code", null);
    }

    /**
     * A八戒UserInfoStr保存
     *
     * @param context
     */
    public static void saveUserInfoStr(Context context, String phone) {
        SharedPreferences preferences = context.getSharedPreferences("SHARE_APP_TAG", 0);
        preferences.edit().putString("UserInfoStr", phone).commit();
    }


    /**
     * A八戒UserInfoStr获取
     *
     * @param context
     * @return
     */
    public static String getUserInfoStr(Context context) {
        SharedPreferences preferences = context.getSharedPreferences("SHARE_APP_TAG", 0);
        return preferences.getString("UserInfoStr", null);
    }

    /**
     * A唐僧UserInfoStr保存
     *
     * @param context
     */
    public static void saveUserInfoStr2(Context context, String phone) {
        SharedPreferences preferences = context.getSharedPreferences("SHARE_APP_TAG", 0);
        preferences.edit().putString("UserInfoStr2", phone).commit();
    }


    /**
     * A八戒UserInfoStr获取
     *
     * @param context
     * @return
     */
    public static String getUserInfoStr2(Context context) {
        SharedPreferences preferences = context.getSharedPreferences("SHARE_APP_TAG", 0);
        return preferences.getString("UserInfoStr2", null);
    }

    /**
     * 保存申请使用时长
     *
     * @param context
     * @param time
     */
    public static void saveUseTime(Context context, int time) {
        SharedPreferences preferences = context.getSharedPreferences("SHARE_APP_TAG", 0);
        preferences.edit().putInt("use_time", time).commit();
    }

    /**
     * 获取使用时长
     *
     * @param context
     * @return
     */
    public static int getUseTime(Context context) {
        SharedPreferences preferences = context.getSharedPreferences("SHARE_APP_TAG", 0);
        return preferences.getInt("use_time", 5);
    }

    /**
     * 获取设备唯一id
     */
    @SuppressLint("MissingPermission")
    public static String getIMEI(Context context) {
        String serial = null;

        String m_szDevIDShort = "35" +

                Build.BOARD.length() % 10 + Build.BRAND.length() % 10 +

                Build.CPU_ABI.length() % 10 + Build.DEVICE.length() % 10 +

                Build.DISPLAY.length() % 10 + Build.HOST.length() % 10 +

                Build.ID.length() % 10 + Build.MANUFACTURER.length() % 10 +

                Build.MODEL.length() % 10 + Build.PRODUCT.length() % 10 +

                Build.TAGS.length() % 10 + Build.TYPE.length() % 10 +

                Build.USER.length() % 10; //13 位

        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                serial = Build.getSerial();
            } else {
                serial = Build.SERIAL;
            }
            //API>=9 使用serial号
            return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
        } catch (Exception exception) {
            //serial需要一个初始化
            serial = "serial"; // 随便一个初始化
        }
        //使用硬件信息拼凑出来的15位号码
        return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
    }

    /**
     * 查网络是否连接
     */
    public static boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            @SuppressLint("MissingPermission") NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable();
            }
        }
        return false;
    }


    /**
     * 获取assets的数据
     *
     * @param context
     * @param fileName
     * @return
     */
    public static String getAssetsInfo(Context context, String fileName) {
        InputStream inputStream;
        InputStreamReader inputStreamReader;
        BufferedReader bufferedReader;
        try {
            StringBuilder stringBuilder = new StringBuilder();
            inputStream = context.getAssets().open("server.json");
            if (inputStream != null) {
                inputStreamReader = new InputStreamReader(inputStream);
                bufferedReader = new BufferedReader(inputStreamReader);
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    stringBuilder.append(line);
                }
            }
            if (!TextUtils.isEmpty(stringBuilder.toString())) {
                JSONObject jsonObject = new JSONObject(stringBuilder.toString());
                String result = jsonObject.optString(fileName, "");
                return result;
            }
        } catch (IOException | JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "";
        }
        return "";
    }

    /**
     * 判断当前app是A唐僧还是A八戒
     *
     * @param context
     * @return
     */
    public static boolean administratorsState(Context context) {
        String administratorsState = BaseUtil.getAssetsInfo(context, "isAdministrators");
        return !TextUtils.isEmpty(administratorsState) && administratorsState.equals("true");
    }

    /**
     * 屏幕息屏 true为打开，false为关闭
     *
     * @param context
     * @return
     */
    public static boolean isScreenOn(Context context) {
        PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        return powerManager.isScreenOn();
    }

    /**
     * 是否解锁 false为解锁
     *
     * @param context
     * @return
     */
    public static boolean isKeyguardManager(Context context) {
        KeyguardManager mKeyguardManager = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
        return mKeyguardManager.inKeyguardRestrictedInputMode();
    }


    /**
     * string时间转long
     *
     * @return
     */
    public static long dataStr2long(String data) {
        SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            return dateformat.parse(data).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 获long时间转String
     *
     * @return
     */
    public static String getLong2StrData(long t) {
        SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateStr = dateformat.format(t);
        return dateStr;
    }

    /**
     * 获取当前时间
     *
     * @return
     */
    public static String getStrData(long t) {
        SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateStr = dateformat.format((System.currentTimeMillis() + t));
        return dateStr;
    }

    /**
     * 是否结束使用
     *
     * @return
     */
    public static boolean isEndUse(String endTime) {
        if (TextUtils.isEmpty(endTime)) {
            return false;
        }
        if (dataStr2long(endTime) < System.currentTimeMillis())
            return false;
        else
            return true;
    }
}
